

from rest_framework import serializers
from goods.models import SKU,SKUSpecification,GoodsCategory,SPU,SPUSpecification,SpecificationOption


class SKUSpecModelSerializer(serializers.ModelSerializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()

    class Meta:
        model = SKUSpecification
        fields = [
            'spec_id',
            'option_id'
        ]


class SKUModelSerializer(serializers.ModelSerializer):

    spu = serializers.StringRelatedField()
    spu_id = serializers.IntegerField()
    category = serializers.StringRelatedField()
    category_id = serializers.IntegerField()

    # 是什么？！
    # 答：是与当前主表(SKU)对象关联的所有从表(SKUSpecification)数据对象
    # 一个还是多个？！
    # 答：多个！
    specs = SKUSpecModelSerializer(many=True)


    class Meta:
        model = SKU
        fields = "__all__" # 非主键隐藏字段不会自动映射

    def create(self, validated_data):
        # 创建sku主表对象以外，还要创建中间表对象来记录规格和选项信息
        specs = validated_data.pop('specs')
        # [{spec_id: "6", option_id: 15}, {spec_id: "7", option_id: 21}]

        # 1、构建SKU对象
        instance = SKU.objects.create(**validated_data)
        # 2、构建SKUSpecification对象
        for temp in specs:
            # temp: {spec_id: "6", option_id: 15}
            temp['sku_id'] = instance.id
            SKUSpecification.objects.create(**temp)

        return instance

    def update(self, instance, validated_data):
        # 更新sku主表对象的同时，还要更新中间表数据来记录规格和选项信息
        specs = validated_data.pop('specs')

        # 默认模型类序列化器的update方法无法构建中间表数据(无法处理specs)
        instance = super().update(instance, validated_data)

        # 更新中间表数据
        # 1删除中间表原有记录；
        SKUSpecification.objects.filter(sku_id=instance.id).delete()
        # 2重新插入新的规格信息;
        for temp in specs:
            # temp: {spec_id: "6", option_id: 15}
            temp['sku_id'] = instance.id
            SKUSpecification.objects.create(**temp)

        return instance




# 分类信息序列化器
class SKUCategorySimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = [
            'id',
            'name'
        ]

# spu序列化器
class SPUSimpleModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = SPU
        fields = [
            'id',
            'name'
        ]



class SpecOptSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = SpecificationOption
        fields = [
            'id',
            'value'
        ]


# 规格信息序列化器
class SPUSpecModelSerializer(serializers.ModelSerializer):
    spu = serializers.StringRelatedField()
    spu_id = serializers.IntegerField()

    # SpecificationOption模型类数据对象；多个！
    options = SpecOptSimpleSerializer(many=True, read_only=True)

    class Meta:
        model = SPUSpecification
        fields = [
            'id',
            'name',
            'spu',
            'spu_id',
            'options'
        ]





















